import React, { useState, useEffect } from 'react';
import { Button, Input, Image } from 'antd';
import { GetCaptchaImg,PostCaptcha } from "@/api/login"

const CaptchaForm = () => {
  const [captchaSrc, setCaptchaSrc] = useState(''); // 验证码图片的URL  
  const [captcha, setCaptcha] = useState(''); // 用户输入的验证码  
  const [captchaError, setCaptchaError] = useState(false); // 验证码输入错误状态  
  const [loading, setLoading] = useState(false); // 提交表单时的加载状态  


  // 获取验证码图片  
  const getCaptcha = async () => {
    try {
      const response= await GetCaptchaImg()
      // console.log(URL.createObjectURL(new Blob([data])))
      // const blob = await response.blob();  
      const url = URL.createObjectURL(response)
      console.log('url', url)
      // const img = document.createElement('img');
      // img.src = url; // url 是你的 Blob URL  
      // document.body.appendChild(img);
      setCaptchaSrc(url)
    } catch (err) {
      console.log(err)
    }
    // 假设你的后端API是 /api/captcha/  
    //     axios.get('/api/captcha/')  
    //       .then(response => {  
    //         setCaptchaSrc(URL.createObjectURL(new Blob([response.data]))); // 假设后端返回的是Blob数据  
    //       })  
    //       .catch(error => {  
    //         console.error('Error fetching captcha:', error);  
    //       });  
  };

  // 刷新验证码  
  const refreshCaptcha = () => {
    setCaptcha(''); // 清空验证码输入  
    setCaptchaError(false); // 重置错误状态  
    getCaptcha(); // 重新获取验证码图片  
  };

  // 提交表单验证验证码  
  const handleSubmit =async () => {
    console.log(captcha)
    try{
      const data =await PostCaptcha({"captcha":captcha})
      console.log(data.status)
    } catch(err){
      console.log(err)
    }
    // setLoading(true);
  };
  // 初始化验证码图片  
  useEffect(() => {
    getCaptcha();
  }, []);

  return (
    <div>
      11
      <img src={captchaSrc} ></img>
      <Image  
        src={captchaSrc}  
        alt="captcha"  
        onClick={refreshCaptcha}  
        style={{ cursor: 'pointer' }} // 添加点击提示  
      />  
      <Input.Password  
        type="text" // 通常验证码不是密码，所以使用text类型  
        placeholder="请输入验证码"  
        value={captcha}  
        onChange={e => setCaptcha(e.target.value)}  
        onPressEnter={handleSubmit} // 当按下Enter键时提交表单  
      />  
      {captchaError && <div style={{ color: 'red', marginTop: '8px' }}>验证码错误</div>}  
      <Button  
        type="primary"  
        onClick={handleSubmit}  
        loading={loading} // 显示加载状态  
        disabled={loading} // 当加载时禁用按钮  
      >  
        提交  
      </Button>  
    </div>
  );
};

export default CaptchaForm;